package site.wuao.simplerxjava.thread;

import android.util.Log;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 线程
 *
 * @author wuao
 * @date 2017.12.07
 * @note -
 * ---------------------------------------------------------------------------------------------------------------------
 * @modified -
 * @date -
 * @note -
 */
public class RxThread {
    /** 标记 */
    private static final String TAG = "RxThread";

    /**
     * newThread
     *
     * @note 1.subscribeOn指定Observable在哪个线程
     * 2.ObserveOn指定Observer在哪个线程
     * 3.Schedulers.newThread()运行在新开的线程
     * 4.AndroidSchedulers.mainThread()运行在主线程
     */
    public void newThread() {
        Observable
                .create(new Observable.OnSubscribe<Integer>() {
                    @Override
                    public void call(Subscriber<? super Integer> subscriber) {
                        Log.i(TAG, "call_Observable: " + Thread.currentThread().getName());
                        subscriber.onNext(1);
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Log.i(TAG, "call_Observer: " + Thread.currentThread().getName());
                    }
                });

        // call_Observable: RxNewThreadScheduler-1
        // call_Observer: main
    }


    /**
     * io
     *
     * @note 多数情况下io比newThread更有效率
     */
    public void io() {
        Observable
                .create(new Observable.OnSubscribe<Integer>() {
                    @Override
                    public void call(Subscriber<? super Integer> subscriber) {
                        Log.i(TAG, "call_Observable: " + Thread.currentThread().getName());
                        subscriber.onNext(1);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        Log.i(TAG, "call_Observer: " + Thread.currentThread().getName());
                    }
                });

        // call_Observable: RxCachedThreadScheduler-1
        // call_Observer: main
    }
}
